export default class Carousel{
    el=null;
    ul=null;
    olli=null;
    index=0;
    timer=null;
    constructor(selector){
        this.el=document.querySelector(selector);
        this.ul=this.el.querySelector("ul");
        this.olli=this.el.querySelectorAll('ol>li');
    }
    slide(){
        let w=this.ul.querySelector('li').offsetWidth;
        let h=this.ul.querySelector('li').offsetHeight;
        this.el.style.height=h+"px";
        let s=-this.index*w;
            this.olli.forEach((v)=>{
                v.className='';
            })
            if(this.index == this.ul.children.length-1){
                this.olli[0].className="active"
            }else{
                this.olli[this.index].className="active"
            }
            this.ul.style.transitionDuration=".7s";
            this.ul.style.transform=`translateX(${s}px)`;
    }
    play(){
        this.timer=setInterval(()=>{
            this.index++;
            this.slide();
        },2000)
        this.addEvent()
    }
    addEvent(){
        this.ul.addEventListener("transitionend",()=>{
            if(this.index == this.ul.children.length-1){
                this.index=0;
                this.ul.style.transitionDuration="0s";
                this.ul.style.transform="translateX(0px)"
            }
        });
        window.onresize=()=>{
            let h=this.ul.querySelector('li').offsetHeight;
            this.el.style.height=h+"px";
        }
        
        let x,moveX,s;
        this.ul.ontouchstart=(e)=>{
            clearInterval(this.timer)
            this.ul.style.transitionDuration="0s";
            x=e.touches[0].clientX;
            console.log(this.index)
        }
        this.ul.ontouchmove=(e)=>{
            moveX=e.touches[0].clientX
            s=moveX-x;
            this.ul.style.left=s+"px";
        }
        this.ul.ontouchend=()=>{
            if(s>60){
                console.log('右')
                this.index--
            }else if(s<60){
                console.log('左')
                this.index++
            }
            this.ul.style.left="0px";
            this.ul.style.transitionDuration="0.7s";
            this.slide();
            this.play()
        }
    }
}